<?php
/**
 * QQAS - share your knowledge to the world!
 *
 * @author		xiaochong0302 <xiaochong0302@gmail.com>
 * @copyright	Copyright (c) 2011, Koogua Studio.
 * @license		http://www.qqas.org/user_guide/license.html
 * @link		http://www.qqas.org
 * @since		Version 1.0
 * @filesource
 */


// ------------------------------------------------------------------------

/**
 * Advertisement class
 *
 * @category	Admin
 */
class AdvertisementAction extends AdminAction
{

	protected $AD;
	protected $Location;
	protected $formats;

	//初始化
	public function _initialize()
	{

		parent::_initialize();
		$this->AD = D('Advertisement');
		$this->Location = D('AdLocation');

		$this->formats = array(
			'html'  => L('ad.format_html'),
			'text'  => L('ad.format_text'),
			'image' => L('ad.format_image'),
			'flash' => L('ad.format_flash'),
		);
		$this->assign('formats', $this->formats);
	}


	//广告列表
	public function adList()
	{
		import('ORG.Util.Page');

		$map = array();
		$parameter = '';
		$where = 1;
		if (isset($_REQUEST['location_id']))
		{
			$map['location_id'] = intval($_REQUEST['location_id']);
			$parameter .= '&location_id='. $_REQUEST['location_id'];
			$where .= ' AND A.location_id='. intval($_REQUEST['location_id']);
		}
		$total = $this->AD->where($map)->count();

		$Page = new Page($total);
		$Page->parameter = $parameter;
		$pagination = $Page->show();

		$prefix = C('DB_PREFIX');
		$order = "ad_id DESC";
		$limit = $Page->firstRow.','.$Page->listRows;

		$sql  = " SELECT A.*, L.* FROM {$prefix}advertisement A ";
		$sql .= " LEFT JOIN {$prefix}ad_location L USING(location_id) ";
		$sql .= " WHERE {$where} ORDER BY {$order}  LIMIT {$limit} ";

		$adList = $this->AD->query($sql);

		$this->assign('pagination', $pagination);
		$this->assign('adList', $adList);

		$this->display();
	}


	//广告批量管理
	public function manageAD()
	{
        if ($this->isPost()) {
			$title = $_POST['title'];
			$status = $_POST['status'];
			$displayOrder = $_POST['display_order'];
			$mods = $_POST['mods'];
			if (!empty($title))
			{
				foreach ($title as $key => $value)
				{
					$data = array(
						'title'         => trim($title[$key]),
					    'status'        => intval($status[$key]),
					);
					$map = array('ad_id' => $key);
					$this->AD->where($map)->save($data);
				}
			}
			if (!empty($mods))
			{
				$where = array('ad_id' => array('in', $mods));
				$this->AD->where($where)->delete();
			}

			$this->AD->cacheAdvertisements();

			$this->success(L('ad.ad_updated_succeed'));
		}
	}


	//添加广告
	public function addAD()
	{
		$this->editAD();
	}


	//编辑广告
	public function editAD()
	{
	    $adID = intval($_REQUEST['ad_id']);
	    $advInfo = $this->AD->find($adID);

		if ($this->isPost())
		{
		    $ad = $_POST['ad'];
		    $format = $_POST['format'];

			switch ($format)
			{
                case 'html':
                    if (empty($ad['html']['code']))
                    {
                    	$this->error(L('ad.required_field_invalid'));
                    }
                    $htmlCode = $ad['html']['code'];
                    break;
                case 'text':
                    if (empty($ad['text']['link']) || empty($ad['text']['title']))
                    {
                    	$this->error(L('ad.required_field_invalid'));
                    }
                    $htmlCode = '<a href="'.$ad['text']['link'].'" target="_blank" '.($ad['text']['size'] ? 'style="font-size: '.$ad['text']['size'].'px"' : '').'>'.$ad['text']['title'].'</a>';
                    break;
                case 'image':
                    if (empty($ad['image']['link']) || empty($ad['image']['file']))
                    {
                    	$this->error(L('ad.required_field_invalid'));
                    }
                    $htmlCode = '<a href="'.$ad['image']['link'].'" target="_blank"><img src="'.$ad['image']['file'].'"'.($ad['image']['height'] ? ' height="'.$ad['image']['height'].'px"' : '').($ad['image']['width'] ? ' width="'.$ad['image']['width'].'px"' : '').($ad['image']['alt'] ? ' alt="'.$ad['image']['alt'].'"' : '').($ad['image']['alt'] ? ' title="'.$ad['image']['alt'].'"' : '').' border="0"></a>';
                    break;
                case 'flash':
                    if (empty($ad['flash']['file']) || empty($ad['flash']['width']) || empty($ad['flash']['height']))
                    {
                    	$this->error(L('ad.required_field_invalid'));
                    }
                    $htmlCode = '<embed width="'.$ad['flash']['width'].'px" height="'.$ad['flash']['height'].'px" src="'.$ad['flash']['file'].'" format="application/x-shockwave-flash"></embed>';
                    break;
            }

            $parameter = serialize(array($format => $ad[$format]));
            $data = array(
            	'location_id'  => $_POST['location_id'],
            	'title'        => $_POST['title'],
            	'format'       => $format,
            	'parameter'    => $parameter,
            	'html_code'    => $htmlCode,
            	'start_time'   => intval(strtotime($_POST['start_time'])),
            	'expire_time'  => intval(strtotime($_POST['expire_time'])),
            );

            if (!empty($adID))
            {
                $map = array('ad_id' => $adID);
            	$this->AD->where($map)->save($data);
            	$message = L('ad.ad_edited_succeed');
            }
            else
            {
            	$adID = $this->AD->add($data);
            	$message = L('ad.ad_added_succeed');
            }

            $this->AD->cacheAdvertisements();

            $this->assign('jumpUrl', __URL__.'/adList');
            $this->success($message);
		}
		else
		{
		    $locations = $this->Location->select();
		    $locationSelected = $advInfo ? $advInfo['location_id'] : 1;
			$this->assign('locations', $locations);
			$this->assign('locationSelected', $locationSelected);

			$advinfo['format'] = !empty($advInfo) ? $advInfo['format'] : 'html';
			$this->assign('formatOptions', $this->formats);
			$this->assign('formatSelected', $advInfo['format']);

			$parameter = isset($advInfo['parameter']) ? $advInfo['parameter'] : array();
			$parameter = unserialize($parameter);
            $advInfo['parameter'] = $parameter[$advinfo['format']];

            $this->assign('rs', $advInfo);

			$this->display('editAD');
		}
	}


	//广告位列表
	public function locationList()
	{
	    import('ORG.Util.Page');

		$where = $order = array();
		$total = $this->Location->where($where)->count();

		$Page = new Page($total);
		$pagination = $Page->show();
		$locationList = $this->Location->where($where)->order($order)->limit($Page->firstRow.','.$Page->listRows)->select();

		$this->assign('pagination', $pagination);
		$this->assign('locationList', $locationList);

		$this->display();
	}


	//添加广告位
	public function addLocation()
	{
		$this->editLocation();
	}


	//编辑广告位
	public function editLocation()
	{
	    $locationID = intval($_REQUEST['location_id']);
	    $location = $this->Location->find($locationID);

        if ($this->isPost())
		{
		    $map = array(
		       'location_id' => array('neq' => $locationID),
		       'identifier'  => trim($_POST['identifier']),
		    );
		    $result = $this->Location->where($map)->find();
            if (!empty($result))
            {
                $this->error(L('ad.loc_existed'));
            }
            if (!preg_match("/^[0-9a-z\-_]+$/i", $_POST['identifier']))
            {
            	$this->error(L('ad.loc_identifier_invalid'));
            }

            $data = array(
                'identifier'  => trim($_POST['identifier']),
                'template'    => trim($_POST['template']),
                'description' => $_POST['description'],
            );

            if (!empty($location))
            {
                $map = array('location_id' => $locationID);
            	$this->Location->where($map)->save($data);
            	$message = L('ad.loc_edited_succeed');
            }
            else
            {
                $data['type'] = 'custom';
                $this->Location->add($data);
                $message = L('ad.loc_added_succeed');
            }
            cache_advertisements();
            $this->assign('jumpUrl', __URL__.'/locationList');
            $this->success($message);
		}
		else
		{
		    $template = '<div style="">{$ad}</div>';
		    $this->assign('template', $template);

		    $this->assign('rs', $location);

		    $this->display('editLocation');
		}
	}


    //删除广告位
    public function deleteLocation()
    {
        $locationID = intval($_REQUEST['location_id']);
        $map = array('location_id' => $locationID);

        $location = $this->Location->find($locationID);
        $ads = $this->AD->where($map)->find();

        if (empty($location) || 'system' == $location['type'])
        {
        	$this->redirect('Admin-Advertisement/locationList');
        }
        if ($ads)
        {
            $this->error(L('loc_deleted_failed'));
        }
        $this->Location->delete($locationID);

        $this->AD->cacheAdvertisements();

        $this->success(L('ad.loc_deleted_succeed'));
    }

}
// End  Class

/* End of file AdvertisementAction.class.php */
/* Location: App/Lib/Action/Admin/AdvertisementAction.class.php */